package server;

import ocsf.server.ConnectionToClient;
import ocsf.server.ObservableServer;

public class Server extends ObservableServer {
	/**
	 * The default port to listen on.
	 */
	final public static int DEFAULT_PORT = 5555;
	
	/**
	 * One db connector at the creation of the server
	 */
	private DBConnector dbc;
	
	/**
	 * One Server Handler at the creation of the server
	 */
	private ServerHandler srvh;

	
	private ServerMaintenance srvm;
	
	private ServerMailBot srvmb;
	
	private ServerReminderBot srvrb;
	
	/**
	  * Constructs an instance of the echo server.
	  *
	  * @param port The port number to connect on.
	  * @param db address, user and password
	  */
	public Server(int port, String db_addr, String db_user, String db_psw) {
		super(port);
		this.dbc = new DBConnector(db_addr, db_user, db_psw);
		this.srvh = new ServerHandler(dbc);
		this.srvm = new ServerMaintenance(srvh);
		this.srvmb = new ServerMailBot(srvh);
		this.srvrb = new ServerReminderBot(srvh);
	}

	/**
	 * This method handles any messages received from the client.
	 *
	 * @param msg The message received from the client.
	 * @param client The connection from which the message originated.
	 */
	public void handleMessageFromClient(Object msg, ConnectionToClient client) {
		srvh.readMsg(msg, client);
	}

	/**
	  * This method overrides the one in the superclass.  Called
	  * when the server starts listening for connections.
	  */
	protected void serverStarted(){
		System.out.println("Server listening for connections on port " + getPort());
		srvm.start();
		srvmb.start();
		srvrb.start();
	}

	/**
	  * This method overrides the one in the superclass.  Called
	  * when the server stops listening for connections.
	  */
	@SuppressWarnings("deprecation")
	protected void serverStopped(){
		srvm.stop();
		srvmb.stop();
		srvrb.stop();
		System.out.println("Server has stopped listening for connections.");
	}

	public static void main(String[] args){
		int port = 0; //Port to listen on
		String db_addr = null;
		String db_user = null;
		String db_psw = null;

		try{
			port = Integer.parseInt(args[0]); //Get port from command line
		}catch(Throwable t){
			port = DEFAULT_PORT; //Set port to 5555
		}
 
		try{
			db_addr = args[1];
		} catch(Throwable t){}
	
		try{
			db_user = args[2];
		} catch(Throwable t){}
 
		try{
			db_psw = args[3];
		} catch(Throwable t){}
 
		Server sv = new Server(port, db_addr, db_user, db_psw);
 
		try {
			sv.listen(); //Start listening for connections
		} catch (Exception ex){
			System.out.println("ERROR - Could not listen for clients!");
		}
	}
}